import {
  ProForm,
  ProFormDateMonthRangePicker,
  ProFormDateRangePicker,
  ProFormDateYearRangePicker,
  QueryFilter,
} from '@/components/Pro';
import { parseArray } from '@/pages/Statistics/Battery/utils';
import { TreeNode } from '@/pages/Statistics/ElectricityConsumption/help';
import { getDeviceCascader } from '@/utils/formatterTree';
import { useModel } from '@@/exports';
import { useIntl } from '@umijs/max';
import { Button, DatePickerProps, Space, TreeSelect } from 'antd';
import { Dayjs } from 'dayjs';
import moment, { Moment } from 'moment';
import React, { useEffect, useRef, useState } from 'react';

interface submitParams {
  stationId?: string | number;
  date: Date[] | Moment[] | Dayjs[] | undefined;
  areaIdList: string[] | number[] | null;
}

type IProps = {
  dateType: string;
  submitForm: (data: submitParams) => void;
};

const ChartForm: React.FC<IProps> = (props) => {
  const { dateType, submitForm } = props;
  const intl = useIntl();
  const { initialState } = useModel('@@initialState');
  const initialValue = () => {
    if (dateType === 'date') return [moment().subtract(6, 'days'), moment().subtract(0, 'days')];
    if (dateType === 'month')
      return [moment().subtract(2, 'months'), moment().subtract(0, 'months')];
    if (dateType === 'year') return [moment().subtract(1, 'years'), moment().subtract(0, 'years')];
  };
  const [selectedDate, setSelectedDate] = useState(initialValue());
  const [treeData, setTreeData] = useState();
  const [isPartitionQuery, setIsPartitionQuery] = useState(false);
  const [dimensions, setDimensions] = useState();
  const selectedType = useRef(null);
  const [areaId, setAreaId] = useState<string[] | number[] | null>(null);
  const formRef = useRef(null);
  const handleDateChange = (value: any) => {
    setSelectedDate(value);
  };
  /**
   * 获得禁用列表
   * @param Nodes
   */
  const setDisabled = (Nodes: TreeNode[]): TreeNode[] => {
    return Nodes.map((node) => {
      const newNode: TreeNode = {
        ...node,
        disabled: selectedType.current === null ? false : node.nodeType !== selectedType.current,
      };
      if (newNode.subDevices) {
        newNode.subDevices = setDisabled(newNode.subDevices);
      }
      return newNode;
    });
  };
  const disabledDate: DatePickerProps['disabledDate'] = (current) => {
    const disabled = current && current >= moment().endOf('day');

    // if (from) {
    //   if (dateType === 'date') return disabled || Math.abs(current.diff(from, 'day')) >= 14;
    //   if (dateType === 'month') return disabled || Math.abs(current.diff(from, 'month')) >= 6;
    //   if (dateType === 'year') return disabled || Math.abs(current.diff(from, 'years')) >= 4;
    // }

    return disabled;
  };
  const getDevicesTree = () => {
    getDeviceCascader(false, 2).then((res) => {
      setDimensions(res[0].uniqueId);
      selectedType.current = 'ROOT';
      setTreeData(setDisabled([res[0]]));
    });
  };
  useEffect(() => {
    getDevicesTree();
    // 初始值
    submitForm({
      date: initialValue(),
      areaIdList: areaId,
    });
  }, []);
  return (
    <>
      <QueryFilter
        layout={'inline'}
        submitter={false}
        style={{ paddingBottom: 0 }}
        formRef={formRef}
      >
        {dateType === 'date' && (
          <ProFormDateRangePicker
            name="date"
            label={intl.formatMessage({ id: 'statistics.income.select' })}
            initialValue={initialValue()}
            fieldProps={{
              disabledDate: disabledDate,
              allowClear: false,
              onChange: handleDateChange,
            }}
          />
        )}
        {dateType === 'month' && (
          <ProFormDateMonthRangePicker
            name="date"
            label={intl.formatMessage({ id: 'statistics.income.select' })}
            initialValue={initialValue()}
            fieldProps={{
              disabledDate: disabledDate,
              allowClear: false,
              onChange: handleDateChange,
            }}
          />
        )}
        {dateType === 'year' && (
          <ProFormDateYearRangePicker
            name="date"
            label={intl.formatMessage({ id: 'statistics.income.select' })}
            initialValue={initialValue()}
            fieldProps={{
              disabledDate: disabledDate,
              allowClear: false,
              onChange: handleDateChange,
            }}
          />
        )}
        {initialState?.isArea && (
          <ProForm.Item label={intl.formatMessage({ id: 'statistics.work.dimensions' })}>
            <TreeSelect
              value={dimensions}
              treeData={treeData}
              multiple={true}
              maxTagCount={'responsive'}
              showSearch={true}
              maxCount={100}
              fieldNames={{
                label: 'deviceName',
                value: 'uniqueId',
                children: 'subDevices',
              }}
              onSelect={(...args) => {
                let selectOptions = args[1];
                if (selectedType.current === null && selectOptions?.nodeType) {
                  selectedType.current = selectOptions?.nodeType;
                  setIsPartitionQuery(selectOptions?.nodeType === 'AREA');
                }
                setTreeData(setDisabled([treeData[0]]));
              }}
              onChange={(...args) => {
                setDimensions(args[0]);
                let selectedOptions = args[1];
                if (!selectedOptions.length) {
                  //清除后不再做相应限制
                  setIsPartitionQuery(false);
                  selectedType.current = null;
                  setTreeData(setDisabled([treeData[0]]));
                }
                let hasAreaNode: boolean = false;
                const ans = parseArray(args[0]);
                if (ans.nodeType.length) {
                  hasAreaNode = ans.nodeType.some((item: string) => {
                    return item === 'AREA';
                  });
                }
                if (hasAreaNode) {
                  setIsPartitionQuery(true);
                  setAreaId(ans.id);
                } else {
                  setIsPartitionQuery(false);
                  setAreaId(null);
                }
              }}
            ></TreeSelect>
          </ProForm.Item>
        )}

        <ProForm.Item>
          <Space>
            <Button
              type={'primary'}
              onClick={() => {
                submitForm({
                  areaIdList: areaId,
                  isPartitionQuery: isPartitionQuery,
                  date: selectedDate,
                });
              }}
            >
              {intl.formatMessage({ id: 'statistics.income.search' })}
            </Button>
            <Button
              onClick={() => {
                setIsPartitionQuery(false);
                setSelectedDate(initialValue());
                setDimensions(treeData[0].uniqueId);
                selectedType.current = 'ROOT';
                setTreeData(setDisabled([treeData[0]]));
                setAreaId(null);
                formRef?.current?.resetFields();
                submitForm({
                  areaIdList: null,
                  isPartitionQuery: false,
                  date: initialValue(),
                });
              }}
            >
              {intl.formatMessage({ id: 'statistics.income.reset' })}
            </Button>
          </Space>
        </ProForm.Item>
      </QueryFilter>
    </>
  );
};

export default ChartForm;
